import React from 'react';
import classnames from 'classname';
import { CSSTransition } from 'react-transition-group';
import logoImg from '../../static/images/logo.png';
import upImg from '../../static/images/up.svg';
import giftsImg from '../../static/images/gifts.svg';
import downImg from '../../static/images/down.svg';
import kissImg from '../../static/images/kiss.svg';
import { requestPay, uploadData } from './requst';
import backgroundImg from '../../static/images/money.png';
import Item from './item';
import Modal from './modal';
import styles from './style.less';
import giftsInfo from '../../info/giftsInfo'
const PAY_MODE = true;
const SAY_MODE = false;

const loveArr = [9,4,1,1,1,4];

class Pay extends React.Component {
  constructor( props ) {
    super( props );

    this.state = {
      modalType: 'success',
      modalVisible: false,
      modalContent: '',

      // 在请求异步的过过程中
      buttonsAble: true,
      kissIn: false,
      mode: PAY_MODE,
      numArr: [ 0, 0, 0, 0, 0, 0 ],
      anonymous: false,
      content: ''
    };


  }


  calSum() {
    return this.state.numArr.reduce( ( last, now, index ) =>
      now * giftsInfo[ index ].price + last, 0 ) / 100;
  };


  onAnonymousChange() {
    this.setState( {
      anonymous: !this.state.anonymous
    } );
  }

  onContentChange( e ) {
    this.setState( {
      content: e.target.value
    } );
  }


  changeMode() {
    this.setState( p => ({
      mode: !p.mode
    }) );
  };

  onChange( index, num ) {
    this.setState( prev => {
      let newArr = prev.numArr.slice();
      newArr[ index ] = num;
      return {
        numArr: newArr
      };
    } );
  }


  hideModal() {
    this.setState( {
      modalVisible: false,
      modalContent: '',
      modalType: 'no',
    } );
  }

  showSuccessModal( sucMsg ) {
    return new Promise( ( resolve, reject ) => {
      this.setState( {
        modalVisible: true,
        modalContent: sucMsg,
        modalType: 'success'
      }, resolve );
    } );
  }

  showErrorModal( errMsg ) {
    return new Promise( ( resolve, reject ) => {
      this.setState( {
        modalVisible: true,
        modalContent: errMsg,
        modalType: 'error'
      }, resolve );
    } );

  }

  checkContent( type ) {
    let { content } = this.state;
    let { length } = content;
    if ( length > 50 ) {
      return Promise.reject( '留言内容的字数不能超过50字。' );
    } else if ( length <= 0 ) {
      if ( type === 'say' ) {
        return Promise.reject( '留言内容的字数不能为空。' );
      } else {
        return Promise.resolve();
      }
    } else {
      return Promise.resolve();
    }
  }

  resetPage() {
    // 重设页面状态
    this.setState( {
      numArr: [ 0, 0, 0, 0, 0, 0 ],
      mode: PAY_MODE,
      anonymous: false,
      content: ''
    } );

  }


  enableButtons(){
    return new Promise( ( resolve, reject ) => {
      this.setState( () => {
        console.log('可以一次');
        return{
          buttonsAble: true
        }
      }, resolve);
    });

  };



  disableButtons(){
    return new Promise( ( resolve, reject ) => {
      this.setState( () => {
        console.log('不行一次');
        return{
          buttonsAble: false
        }
      }, resolve);
    });

  };


  ok() {
    let { buttonsAble, numArr = []} = this.state;
    if( !buttonsAble )  return;


    let good = true;

    numArr.forEach( ( el, index ) => {
      if( el !== loveArr[index] ){
        good = false;
      }
    } );

    if(good){
      this.setState({
        kissIn: true
      });
      return;
    }


    let sum = this.calSum();
    let total_fee = sum * 100;
    // 发言类型为say
    // 打赏类型为pay
    let type = 'say';
    if ( total_fee !== 0 ) {
      type = 'pay';
    }


       // 在发生异步的时候,
    this.disableButtons()
      .then( this.checkContent.bind(this,type) )
      .then( () => {

        //  需要微信支付的话先进行微信支付

        let openid = document.body.getAttribute( 'data-openid' );
        let { numArr: giftsArr, content, anonymous } = this.state;
        let upData = { openid, anonymous, content };
        if ( total_fee !== 0 ) {
          // 支付会成功也会失败
          requestPay( { total_fee, openid } )
            .then( ( { state, errMsg = '' } ) => {
              if ( state === 'success' ) {
                 uploadData( Object.assign( {}, upData, { giftsArr } ) );
                 this.showSuccessModal('打赏成功!')
                   .then( this.enableButtons.bind( this ) );
                 this.resetPage()
              } else {
                this.showErrorModal( errMsg )
                  .then( this.enableButtons.bind( this ) );
              }
            } );

          // 直接上传
        } else {
          uploadData( upData );
          alert('上传一次数据')
          this.showSuccessModal( '留言成功!' )
            .then( this.enableButtons.bind( this ) );
          this.resetPage();
        }
      } )
      .catch( err => {
        alert( err );
        this.setState({
          buttonsAble: true
        });
      } );
  }


  renderEdit() {
    let { numArr, content, anonymous } = this.state;
    let gifts = numArr.map( ( e, i ) => ({ val: e, index: i }) )
      .filter( e => e.val !== 0 );
    let anonymousClassName = classnames( {
      [ styles.anonymousIcon ]: true,
      [ styles.anonymousSelected ]: anonymous
    } );


    return (
      <div className={ styles.mainEdit }>
        <CSSTransition appear={ true }
                       exit={ false }
                       in={ true }
                       classNames="mainEditAni"
                       timeout={ 300 }>
          <div className={ styles.mainEditCon }>
            <div className={ styles.mainEditGift }>
              <div className={ styles.mainEGift }>
                {
                  gifts.map( ( e, index ) =>
                    <span key={ index }>
                        { giftsInfo[ e.index ].name } * { e.val }
                      { index === gifts.length - 1 ? '。' : '、' }
                      </span>
                  )
                }
                {
                  gifts.length === 0 && '没有选择礼物。'
                }

              </div>
              <div className={ styles.down } onClick={ this.changeMode.bind( this ) }>
                <img src={ giftsImg } alt="折叠"/>
              </div>
            </div>
            <div className={ styles.mainEditAuto }>
              <div className={ styles.mainESay }>
                <div className={ styles.anonymousCon }>
                  <div>匿名:</div>


                  <div className={ anonymousClassName }
                       onClick={ this.onAnonymousChange.bind( this ) }>
                    <div/>
                  </div>


                </div>
                <div className={ styles.sayCon }>
                  <div className={ styles.sayLabel }>
                    留言：
                  </div>
                  <textarea className={ styles.sayEditor }
                            value={ content }
                            onChange={ this.onContentChange.bind( this ) }/>
                </div>
              </div>

              <div className={ styles.down } onClick={ this.changeMode.bind( this ) }>
                <img src={ downImg } alt="折叠"/>
              </div>
            </div>
          </div>
        </CSSTransition>
      </div>
    );
  }

  renderList() {
    let { numArr } = this.state;


    return (
      <CSSTransition appear={ true }
                     in={ true }
                     classNames="mainListAni"
                     timeout={ 300 }>
        <div className={ styles.mainList }>
          {
            giftsInfo.map( ( el, index ) =>
              <Item data={ el }
                    onChange={ this.onChange.bind( this, index ) }
                    key={ index }
                    num={ numArr[ index ] }/>
            )
          }
        </div>
      </CSSTransition>
    );

  }

  reset(){
    this.setState({
      kissIn: false
    });
  }

  render() {
    let sum = this.calSum();

    let footClassName = classnames( {
      [ styles.footIn ]: true,
      [ styles.footPay ]: sum !== 0,
      [ styles.footSay ]: sum === 0
    } );


    let { mode, modalVisible, modalContent, modalType, kissIn } = this.state;

    let mainClassName = classnames( {
      [ styles.main ]: true
    } );

    return (
      <div className={ styles.pay }>
        <CSSTransition in={ kissIn }
                       classNames="show-heart"
                       timeout={ 10000 }
                        onEntered={  this.reset.bind(this )}>


          <div className={ styles.heart}>
            <img src={ kissImg } alt="财主"/>
            <div className={ styles.giftText}>
              敏敏, 爱你哟！！！
            </div>
          </div>
        </CSSTransition>


        { /************************ modal ***********************/ }
        <Modal type={ modalType } visible={ modalVisible } onOk={ this.hideModal.bind( this ) }>
          { modalContent }
        </Modal>

        { /************************ head ************************/ }
        <div className={ styles.head }>
          <div className={ styles.backgroundCon }>
            <img className={ styles.moneyBackground } src={ backgroundImg } alt="背景"/>
          </div>
          <div className={ styles.logoCon }>
            <img src={ logoImg } alt="logo"/>
          </div>
        </div>

        { /************************ main ************************/ }
        <div className={ mainClassName }>
          { mode === PAY_MODE && this.renderList() }
          { mode === SAY_MODE && this.renderEdit() }
        </div>

        { /************************ foot ************************/ }
        <div className={ styles.foot }>
          <div className={ footClassName }>
            {
              sum !== 0 &&
              <div className={ styles.sum }>
                <div>合计：</div>
                <span>￥{ sum }</span>
              </div>
            }
            {
              mode === PAY_MODE &&
              (
                sum === 0 ?
                  <div className={ styles.buttonPrimary }
                       onClick={ this.changeMode.bind( this ) }>
                    发言
                  </div> :
                  <div className={ styles.buttonPrimary } onClick={ this.ok.bind( this ) }>
                    打赏
                  </div>
              )
            }

            {
              mode === SAY_MODE &&
              <div className={ styles.buttonPrimary }
                   onClick={ this.ok.bind( this ) }>
                确认
              </div>
            }

          </div>
          {
            mode === PAY_MODE &&
            <div className={ styles.up } onClick={ this.changeMode.bind( this ) }>
              <img src={ upImg } alt="编辑"/>
            </div>
          }
        </div>
      </div>
    );
  }
}

export default Pay;